import _ from 'lodash'

/**
 * 根据索引id 获取菜单
 * @param {*} menuList 总菜单列表
 * @param {*} index 索引id
 */

function getCurrentBreadcrumbList(menuList, index) {
  const arr = []

  const ids = index.split('-')

  const len = ids.length - 1

  function push(list, ids, i) {
    if (i <= len) {
      const item = list[ids[i] - 1]
      const next = _.cloneDeep(item)

      next.children = null
      arr.push(next)
      push(item.children, ids, i + 1)
    }
  }
  push(menuList, ids, 1)

  return arr
}

/**
 * 添加 tagsView
 * @param {*} tagsViewList
 * @param {*} item
 */
function addTagsViewItem(tagsViewList, item) {
  const index = indexOf(tagsViewList, item.id)
  if (index === -1) {
    const _item = _.cloneDeep(item)
    _item.children = null
    tagsViewList.push(_item)
  }
}

/**
 * 移除 tagsView
 * @param {*} tagsViewList
 * @param {*} id
 */
function removeTagsViewItem(tagsViewList, cur, item) {
  let res = null
  const index = indexOf(tagsViewList, item.id)

  if (index !== -1) {
    tagsViewList.splice(index, 1)
    if (item.id === cur.id) {
      const len = tagsViewList.length
      if (index >= len) {
        res = tagsViewList[len - 1]
      } else {
        res = tagsViewList[index]
      }
    }
  }
  return res
}

/**
 * 查找指定元素
 * @param {*} list
 * @param {*} item
 */
function indexOf(list, item) {
  let index = -1
  if (list !== null && item !== null && list.length > 0) {
    list.forEach((ele, i) => {
      if (ele.id === item) {
        index = i
      }
    })
  }
  return index
}

export default {
  getCurrentBreadcrumbList,
  addTagsViewItem,
  removeTagsViewItem,
  indexOf
}
